import go from 'gojs'
import request from '@/utils/request'
import vdcApi from '@/api/vdcApi.js'
import vmApi from '@/api/vmApi'
import networkApi from '@/api/networkApi'
import echarts from 'echarts'

/**
 * 创建磋商任务
 * cloudPlatformIds 云平台逗号分割
 * @returns {*}
 */

export async function createConsult(cloudPlatformIds, privateIds) {
  return new Promise((resolve, reject) => {
    request({
      url: '/cloud/jcce/v1.0/consult/createConsult',
      method: 'post',
      params: {
        cloudPlatformIds: cloudPlatformIds,
        privatePlatformIds: privateIds
      }
    }).then(data => {
      resolve(data);
    })
  })
}

/**
 * 概览列表
 * @returns {*}
 */
export function consultList() {
  return request({
    url: '/cloud/jcce/v1.0/kt1/overview2',
    // url: 'http://10.4.67.37:28081/jcce/v1.0/kt1/overview2',
    method: 'get'
  })
}

/**
 * 实例
 * @param dataCenterId
 * @returns {*}
 */
export function vmList(dataCenterId) {
  return request({
    url: '/cloud/jcce/v1.0/kt1/vms',
    method: 'get',
    params: {
      dataCenterId: dataCenterId
    }
  })
}

/**
 * 硬盘
 * @param dataCenterId
 * @returns {*}
 */
export function volumnList(dataCenterId) {
  return request({
    url: '/cloud/jcce/v1.0/kt1/volumns',
    method: 'get',
    params: {
      dataCenterId: dataCenterId
    }
  })
}

/**
 * 数据盘
 * @param dataCenterId
 * @returns {*}
 */
export function dataVolumnList(dataCenterId) {
  return request({
    url: '/cloud/jcce/v1.0/kt1/volumns',
    method: 'get',
    params: {
      dataCenterId: dataCenterId
    }
  })
}

/**
 * 数据库
 * @param dataCenterId
 * @returns {*}
 */
export function databaseList(dataCenterId) {
  return request({
    url: '/cloud/jcce/v1.0/kt1/rds',
    method: 'get',
    params: {
      dataCenterId: dataCenterId
    }
  })
}

/**
 * 中间件
 * @param dataCenterId
 * @returns {*}
 */
export function middlewareList(dataCenterId) {
  return request({
    url: '/cloud/jcce/v1.0/kt1/rds',
    method: 'get',
    params: {
      dataCenterId: dataCenterId
    }
  })
}

/**
 * 网络
 * @param dataCenterId
 * @returns {*}
 */
export function vpcList(dataCenterId) {
  return request({
    url: '/cloud/pub/v1.0/vpc/getVpcList',
    method: 'get',
    params: {
      dataCenterId: dataCenterId
    }
  })
}

export default {
  name: 'consult',
  data() {
    return {
      selectedSupplier: [],
      selectedPrivateSupplier: [],
      dataListNew: [],
      selectedSupplierList: [],
      drawerVisible: false,
      databaseList: [
        {
          id: 0,
          name: '云数据库 RDS MySQL 版',
          childList: []
        }
      ],
      dataList: [], // 数据列表
      privateDataList: [], // 私有云商列表
      graphData: [],
      graphLinkData: [],
      showGraph: false,
      imgSingleNormal: '/static/kt1/OWFS_DOWN.png',
      imgSingleConnect: '/static/kt1/OWFS.png',
      imgSingleConsult: '/static/kt1/OWFS_DOWN_WARNING.png',
      imgGroup: '/static/kt1/SPARK_STREAMING.png',
      detailDialogVisible: false,
      detailData: {},
      detailDataIdx: 0,
      drawerTableData: [],
      drawerTableColumn: [],
      drawerTitle: '',
      drawerIsLoading: false
    }
  },
  mounted() {
    this.getDataList()
  },
  watch: {
    dataListNew: {
      deep: true,
      handler(val) {
        this.selectedSupplier = val.filter(item => item.type === '公有云')
          .flatMap(item => item.initList.filter(ins => ins.checked));
        this.selectedPrivateSupplier = val.filter(item => item.type === '私有云')
          .flatMap(item => item.initList.filter(ins => ins.checked));

        // 计算资源总量
        const totalResources = this.calculateTotalResources(val);
      }
    },
    // 点击图的节点
    detailData: function () {
      for (let i in this.dataList) {
        if (this.dataList[i].id == this.detailData.cloudPlatformId) {
          this.detailDataIdx = i
          break
        }
      }
    }
  },
  methods: {
    change() {
      this.$forceUpdate()
    },
    // 计算右侧饼状图
    calculateTotalResources(data) {
      const totals = {
        cpu: {used: 0, total: 0},
        memory: {used: 0, total: 0},
        storage: {used: 0, total: 0}
      };

      data.forEach(cloud => {
        cloud.props.forEach(prop => {
          totals[prop.type].used += prop.value;
          totals[prop.type].total += prop.total;
        });
      });

      const up_chart = echarts.init(document.getElementById('up_chart'), 'dark')
      const mid_chart = echarts.init(document.getElementById('mid_chart'), 'dark')
      const down_chart = echarts.init(document.getElementById('down_chart'), 'dark')
      const up_option = {
        backgroundColor: 'rgba(0, 0, 0, 0)', // 设置透明背景
        title: { text: 'CPU使用量', left: 'center', top: 'center',
          textStyle: {color: '#ffffff', fontStyle: 'normal', fontWeight: 'bold', fontSize: 12}
        },
        tooltip: {trigger: 'item'}, grid: {left: '0%', containLabel: true},
        series: [{
          name: 'CPU使用量', type: 'pie', radius: ['40%', '70%'],
          data: [{value: totals.cpu.used, name: '已用资源', itemStyle: {color: 'rgb(103, 194, 58)'}},
            {value: totals.cpu.total - totals.cpu.used, name: '未用资源', itemStyle: {color: '#409eff'}}]
        }]
      };
      const mid_option = {
        backgroundColor: 'rgba(0, 0, 0, 0)', // 设置透明背景
        title: { text: '内存使用量', left: 'center', top: 'center',
          textStyle: {color: '#ffffff', fontStyle: 'normal', fontWeight: 'bold', fontSize: 12}
        },
        tooltip: {trigger: 'item'}, grid: {left: '0%', containLabel: true},
        series: [{
          name: '内存使用量', type: 'pie', radius: ['40%', '70%'],
          data: [{value: totals.memory.used, name: '已用资源', itemStyle: {color: '#f5b000'}},
            {value: totals.memory.total - totals.memory.used, name: '未用资源', itemStyle: {color: '#6495ED'}}]
        }]
      };
      const down_option = {
        backgroundColor: 'rgba(0, 0, 0, 0)', // 设置透明背景
        title: { text: '存储使用量', left: 'center', top: 'center',
          textStyle: {color: '#ffffff', fontStyle: 'normal', fontWeight: 'bold', fontSize: 12}
        },
        tooltip: {trigger: 'item'}, grid: {left: '0%', containLabel: true},
        series: [{
          name: '存储使用量', type: 'pie', radius: ['40%', '70%'],
          data: [{value: totals.storage.used, name: '已用资源', itemStyle: {color: '#f5b000'}},
            {value: totals.storage.total - totals.storage.used, name: '未用资源', itemStyle: {color: '#6495ED'}}]
        }]
      };
      up_chart.setOption(up_option)
      mid_chart.setOption(mid_option)
      down_chart.setOption(down_option)
    },
    doConsult() {
      let ids = this.selectedSupplier.map(s => s.id).join(",")
      let privateIds = this.selectedPrivateSupplier.map(s => s.id).join(",")
      // 创建磋商任务
      createConsult(ids, privateIds).then(res => {
        this.$message.success("磋商成功")
        this.$router.push({ name: "磋商过程" })
      })
    },
    handleCheckboxChange(item) {
      if (item.checked) {
        let list = []
        // 将下拉列表的选中状态设置为全部选中
        item.initList.forEach(option => {
          // this.$set(option, 'checked', true);
          list.push(option.id)
          option.checked = true;

        });
        this.$set(item, 'selectedSupplierList', list)
      }
      else {
        item.initList.forEach(option => {
          option.checked = false;
        })
        this.$set(item, 'selectedSupplierList', [])
      }

      // 增加点击云商 下方配额等都展示出来
      for (let idx in item.props) {
        item.props[idx].test = true
        item.props[idx].test3 = item.props[idx].total
        item.props[idx].test5 = 0
      }
    },
    handleCascaderChange(item) {
      // 检查所有选项是否都被选中
      const allSelected = item.selectedSupplierList.length === item.initList.length;
      const list = item.initList.filter(i => item.selectedSupplierList.find(j => i.id === j[0])).map(item => item.id);
      item.initList.forEach(item => {
        if (list.includes(item.id)) {
          item.checked = true;
        }
        else {
          item.checked = false
        }
      })
      // const allSelected = item.initList.every(option => option.checked);
      if (allSelected) {
        // 将 el-checkbox 的选中状态设置为 true
        this.$set(item, 'checked', true);
      }
      else {
        this.$set(item, 'checked', false);
      }
    },
    customColorMethod(percentage) {
      if (percentage < 70) {
        return '#67C23A';
      } else if (percentage < 80) {
        return '#E6A23C';
      } else {
        return '#F56C6C';
      }
    },
    getDataList() {
      this.dataList = []
      consultList().then((data) => {
        this.dataListNew = data.data
      }).catch((error) => {
        console.log(error)
      })
    },
    async getGraphData() {
      let ids = this.selectedSupplier.map(s => s.id).join(",")
      let privateIds = this.selectedPrivateSupplier.map(s => s.id).join(",")

      console.log('ids:' + ids)
      console.log('privateIds:' + privateIds)

      // 创建磋商任务
      let res = await createConsult(ids, privateIds)
      console.log("create:")
      console.log(res)

      this.graphLinkData = res.data.graphLinkDataList
      this.graphData = res.data.graphDataList

      if (this.graphData.length > 0) {
        if (this.graphData[0].childList) {
          this.detailData = this.graphData[0].childList[0]
        } else {
          this.detailData = this.graphData[0]
        }
      }
    },
    chooseMenuItem(item, activeIndex) {
      item.isLoading = true
      switch (activeIndex) {
        case 'network':
          vpcList(item.id).then((data) => {
            item.networkList = data.data.pageData
            item.showFlag = activeIndex
            item.isLoading = false
          })
          break
        case 'instance':
          vmList(item.id).then((data) => {
            item.instanceList = data.data.type
            item.showFlag = activeIndex
            item.isLoading = false
          })
          break
        case 'disk':
          volumnList(item.id).then((data) => {
            item.diskList = data.data.type
            item.showFlag = activeIndex
            item.isLoading = false
          })
          break
        case 'dataDisk':
          volumnList(item.id).then((data) => {
            item.dataDiskList = data.data.type
            item.showFlag = activeIndex
            item.isLoading = false
          })
          break
        case 'database':
          databaseList(item.id).then((data) => {
            this.databaseList[0].childList = data.data
            item.databaseList = this.databaseList
            item.showFlag = activeIndex
            item.isLoading = false
          })
          break
        /*        case 'middleware':
                  middlewareList(item.id).then((data) => {
                    this.databaseList[0].childList = data.data
                    item.middlewareList = this.databaseList
                    item.showFlag = activeIndex
                    item.isLoading = false
                  })
                  break*/
        default:
          break
      }
    },
    choosePrivateMenuItem(item, activeIndex) {
      item.showFlag = activeIndex
    },
    // 点击磋商按钮
    async initGraph() {
      const self = this
      await this.getGraphData()

      var $$ = go.GraphObject.make
      const nodes = []
      const links = this.graphLinkData

      for (let i = 0; i < this.selectedSupplier.length; i++) {
        for (let j = 0; j < this.graphData.length; j++) {
          if (this.graphData[j].id === this.selectedSupplier[i].id) {
            this.graphData[j].state = 2
          }
        }

      }

      console.log(links)
      for (let i = 0; i < this.graphData.length; i++) {
        if (this.graphData[i].childList) {
          nodes.push({
            key: this.graphData[i].id,
            text: this.graphData[i].name,
            source: this.getNodeImg(this.graphData[i]),
            isGroup: true
          })
          for (let j = 0; j < this.graphData[i].childList.length; j++) {
            nodes.push({
              key: this.graphData[i].childList[j].id,
              text: this.graphData[i].childList[j].name,
              source: this.imgSingleConnect,
              group: this.graphData[i].id,
              detailData: this.graphData[i].childList[j]
            })
          }
        } else {
          nodes.push({
            key: this.graphData[i].id,
            text: this.graphData[i].name,
            source: this.getNodeImg(this.graphData[i]),
            detailData: this.graphData[i]
          })
        }
      }
      console.log(nodes)

      const mygoChart = document.getElementById('diagramDiv')
      console.log(mygoChart)
      const diagramParentDiv = document.getElementById('diagramParentDiv')
      diagramParentDiv.removeChild(mygoChart)
      const div = document.createElement('div')
      div.setAttribute('id', 'diagramDiv')
      div.setAttribute('style', 'width:100%; height:90vh')
      diagramParentDiv.appendChild(div)
      this.dataDiagram = $$(go.Diagram, 'diagramDiv', {
        // layout: $$(go.GridLayout)
        'toolManager.mouseWheelBehavior': go.ToolManager.WheelZoom,
        initialAutoScale: go.Diagram.Uniform,
        // start everything in the middle of the viewport
        initialContentAlignment: go.Spot.Center,
        // disable user copying of parts
        allowCopy: false,
        layout: $$(go.CircularLayout, {
          // layerSpacing: 40,
          // columnSpacing: 20,
          // direction: 0,
          // setsPortSpots: false
          // initializeOption:go.LayeredDigraphLayout.InitNaive,
          // layeringOption:go.LayeredDigraphLayout.LayerLongestPathSink
        })
      })
      this.dataDiagram.groupTemplate = $$(
        go.Group,
        'Auto',
        {
          isSubGraphExpanded: false,
          wasSubGraphExpanded: false
        },
        $$(go.Shape, 'Rectangle', { fill: null, stroke: 'rgba(255,255,255,0)' }),
        $$(
          go.Panel,
          'Table',
          $$('SubGraphExpanderButton', { row: 0, column: 0, margin: 3 }),
          $$(
            go.TextBlock,
            {
              row: 1,
              columnSpan: 20,
              stroke: '#ffffff',
              font: 'bold 14px sans-serif',
              textAlign: 'center',
              margin: 5,
              desiredSize: new go.Size(100, 20),
              stretch: go.GraphObject.Horizontal
            },
            new go.Binding('text'),
          ),
          $$(go.Picture, { row: 0, column: 1, desiredSize: new go.Size(60, 60), stretch: go.GraphObject.Horizontal }, new go.Binding('source')),
          $$(
            go.Placeholder,
            { row: 2, columnSpan: 3, padding: 10, alignment: go.Spot.TopLeft },
            new go.Binding('padding', 'isSubGraphExpanded', function (exp) {
              return exp ? 10 : 0
            })
          )
        )
      )
      this.dataDiagram.linkTemplate = $$(
        go.Link,
        {
          curve: go.Link.Bezier
        },
        $$(
          go.Shape,
          {
            strokeWidth: 2,
            name: 'PIPE',
            strokeDashArray: [5, 5]
          },
          new go.Binding('stroke', 'state', (f) => {
            return colorSet(f)
          })
        ),
        $$(
          go.Shape,
          { toArrow: 'Standard', stroke: '#eeeeee', scale: 1 },
          new go.Binding('stroke', 'state', (f) => {
            return colorSet(f)
          }), new go.Binding('visible', 'state', this.pictureVisible)
        ),
        $$(
          go.TextBlock,
          {
            textAlign: 'center',
            font: '16pt helvetica, arial, sans-serif',
            segmentOffset: new go.Point(0, 10),
            margin: 4,
            editable: false
          },
        )
      )

      this.dataDiagram.nodeTemplate = $$(
        go.Node,
        'Vertical',
        {
          click: function (e, node) {
            if (node.data.detailData) {
              self.detailData = node.data.detailData
              self.detailDialogVisible = true
            }
          }
        },
        $$(go.Panel, 'Auto',
          $$(go.Shape, 'RoundedRectangle',
            {
              fill: null, // 设置内部填充的颜色
              stroke: 'rgba(255,255,255,0)'// 设置边框的颜色
            }
          ),
          $$(go.Panel, 'Table',
            $$(go.Picture, { row: 0, column: 0, rowSpan: 2, desiredSize: new go.Size(60, 60) }, new go.Binding('source')),
            $$(go.TextBlock, { row: 2, column: 0, rowSpan: 2, alignment: go.Spot.Top, margin: 5, font: 'bold 14px sans-serif ', stroke: '#ffffff' }, new go.Binding('text'))
          )
        ),
      )
      function colorSet(param) {
        switch (param) {
          case 0: return 'white'
          case 1: return '#ffaa3d'
          default: return '#6e6e6e'
        }
      }
      this.dataDiagram.model = new go.GraphLinksModel(nodes, links)
      console.log(this.selectedSupplier)
      this.showGraph = true
      this.linkLoop()
    },
    quitGraph() {
      for (let i = 0; i < this.dataList.length; i++) {
        this.dataList[i].checked = false
      }
      this.showGraph = false
    },
    getNodeImg(node) {
      if (node.childList) {
        return this.imgGroup
      } else {
        if (node.state === 0) {
          return this.imgSingleNormal
        } else if (node.state === 1) {
          return this.imgSingleConnect
        } else {
          return this.imgSingleConsult
        }
      }
    },
    pictureVisible(key, e) {
      const state = e.part.data.state
      return state === 0
    },
    linkLoop() {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        const oldskips = this.dataDiagram.skipsUndoManager
        this.dataDiagram.skipsUndoManager = true
        this.dataDiagram.links.each(function (link) {
          const shape = link.findObject('PIPE')
          const off = shape.strokeDashOffset - 2
          shape.strokeDashOffset = off <= 0 ? 20 : off
          // speed = parseInt(link.jb.flow);
        })
        this.dataDiagram.skipsUndoManager = oldskips
        this.linkLoop()
      }, 200)
    },
    cutString(str, len) {
      if (str.length * 2 <= len) { //length属性读出来的汉字长度为1
        return str;
      }
      var strlen = 0;
      var s = "";
      for (var i = 0; i < str.length; i++) {
        s = s + str.charAt(i);
        if (str.charCodeAt(i) > 128) {
          strlen = strlen + 2;
          if (strlen >= len) {
            return s.substring(0, s.length - 1) + "...";
          }
        } else {
          strlen = strlen + 1;
          if (strlen >= len) {
            return s.substring(0, s.length - 2) + "...";
          }
        }
      }
      return s;
    }
  }
}
